/**
 *
 */
package info.motteke.kurumi.swt;

import info.motteke.mixivoice4j.Entry;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;

final class ImageSelectionListener extends SelectionAdapter {

    private final Composite base;

    private final SwtImageCache imageCache;

    public ImageSelectionListener(Composite base, SwtImageCache imageCache) {
        this.base = base;
        this.imageCache = imageCache;
    }

    @Override
    public void widgetSelected(SelectionEvent e) {
        Entry entry = (Entry)base.getData();
        Shell shell = new Shell(base.getShell(), SWT.APPLICATION_MODAL | SWT.TITLE | SWT.CLOSE);
        shell.setText(entry.getBody().toString());
        Label label = new Label(shell, SWT.BORDER);
        String url = entry.getImageUrl().getUrl();
        Image image = imageCache.getImage(url);
        label.setImage(image);
        ImageData data = image.getImageData();
        label.setSize(data.width, data.height);

        shell.open();
        shell.pack();
        Display display = shell.getDisplay();

        while (!shell.isDisposed()) {
            if(!display.readAndDispatch()){
                display.sleep();
            }
        }
    }
}